﻿using LXD.StudnetMangement.Models;
using LXD.StudnetMangement.ViewModels;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace LXD.StudnetMangement.Controllers
{
    public class HomeController : Controller
    {
        private readonly IStudentRepository _studentRepository;
        private readonly HostingEnvironment hostingEnvironment;
        private readonly ILogger logger;

        public HomeController(IStudentRepository studentRepository, HostingEnvironment hostingEnvironment,ILogger<HomeController> logger)
        {
            this._studentRepository = studentRepository;
            this.hostingEnvironment = hostingEnvironment;
            this.logger = logger;
        }
        public IActionResult Index()
        {
            IEnumerable<Student> list = _studentRepository.GetAllStudents();
            return View(list);
        }

        public ObjectResult Test()
        {
            Student model = _studentRepository.GetStudent(1);
            return new ObjectResult(model); //ObjectResult 内容协商的
        }

        public IActionResult Details(int? id)
        {
            logger.LogTrace("Trace(跟踪) Log");
            logger.LogDebug("Debug(调试) Log");
            logger.LogInformation("信息(Information) Log");
            logger.LogWarning("警告(Warning) Log");
            logger.LogError("错误(Error) Log");
            logger.LogCritical("严重(Critical) Log");
            //throw new Exception("此异常发生在Details试图中");

            HomeDetailsViewModel homeDetailsViewModel = new HomeDetailsViewModel()
            {
                Student = _studentRepository.GetStudent(id ?? 1),
                PageTiltle = "学生详情"
            };
            return View(homeDetailsViewModel);
        }

        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(StudentCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.Photos != null && model.Photos.Count > 0)
                {

                    uniqueFileName = ProcessUploadeFile(model);

                }
                Student newStudet = new Student
                {
                    Name = model.Name,
                    Email = model.Email,
                    ClassName = model.ClassName,
                    PhotoPath = uniqueFileName
                };
                _studentRepository.Add(newStudet);
                return RedirectToAction("Details", new { id = newStudet.ID });
            }
            return View();

        }

        public RedirectToActionResult Delete(int? id)
        {
            Student del = _studentRepository.Del(id.Value);
            return RedirectToAction("Index", new { });

        }

        [HttpGet]
        public ViewResult Edit(int id)
        {
            Student student = _studentRepository.GetStudent(id);
            StudentEditViewModel studentEditViewModel = new StudentEditViewModel
            {
                ID = student.ID,
                Name = student.Name,
                Email = student.Email,
                ClassName = student.ClassName,
                ExistingPhotoPath = student.PhotoPath
            };
            return View(studentEditViewModel);
        }

        [HttpPost]
        public IActionResult Edit(StudentEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                Student student = _studentRepository.GetStudent(model.ID);
                student.Email = model.Email;
                student.Name = model.Name;
                student.ClassName = model.ClassName;


                if (model.Photos.Count > 0)
                {
                    if (model.ExistingPhotoPath != null)
                    {
                        string filePath = Path.Combine(hostingEnvironment.WebRootPath, "images", model.ExistingPhotoPath);
                        System.IO.File.Delete(filePath);
                    }
                    student.PhotoPath = ProcessUploadeFile(model);
                }

                Student updateStudent = _studentRepository.Update(student);
                return RedirectToAction("Index");
            }

            return View(model);
        }

        /// <summary>
        /// 将照片保存指定路径中
        /// </summary>
        /// <returns></returns>
        private string ProcessUploadeFile(StudentCreateViewModel model)
        {
            string uniqueFileName = null;

            if (model.Photos.Count > 0)
            {
                foreach (var photo in model.Photos)
                {
                    //必须将图片上次到wwwroot中的image文件夹
                    //而要获取wwwroot文件夹路径，我们需要注入ASP.NET Core 提供的hostingEnvironment
                    //通过hostingEnvironment 服务去获取wwwroot文件夹路径
                    string uploadsFolader = Path.Combine(hostingEnvironment.WebRootPath, "images");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName;
                    string filePath = Path.Combine(uploadsFolader, uniqueFileName);
                    //因为使用了非托管资源，所以需要手动进行释放
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        //客户端的文件复制到服务器指定的文件夹里
                        photo.CopyTo(fileStream);
                    }


                }
            }

            return uniqueFileName;
        }
    }
}
